import { useCallback, useRef, useState } from 'react'
import { locateCity, type LocationResult } from './amap'

export function useAMapLocation() {
    const [city, setCity] = useState<string>('')
    const [province, setProvince] = useState<string>('')
    const [district, setDistrict] = useState<string>('')
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<string>('')
    const lastReqRef = useRef<number>(0)

    const getLocation = useCallback(async () => {
		const reqId = Date.now()
		lastReqRef.current = reqId
		setLoading(true)
		setError('')
		try {
			const res: LocationResult = await locateCity()
			if (lastReqRef.current !== reqId) return
			setCity(res.city)
            setProvince(res.province || '')
            setDistrict(res.district || '')
			return res
		} catch (e: any) {
			if (lastReqRef.current !== reqId) return
			setError(e?.message || '定位失败')
			throw e
		} finally {
			if (lastReqRef.current === reqId) setLoading(false)
		}
	}, [])

    return { city, province, district, loading, error, getLocation }
}

export default useAMapLocation


